package com.ctg.itrdc.imageconsole.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.ctg.itrdc.imageconsole.common.util.TimeUtils;
import com.ctg.itrdc.imageconsole.data.constant.CommonConst;
import com.ctg.itrdc.imageconsole.data.dao.IDockerAppImageDao;
import com.ctg.itrdc.imageconsole.data.dao.IDockerAppTypeDao;
import com.ctg.itrdc.imageconsole.data.dao.IDockerImageDao;
import com.ctg.itrdc.imageconsole.data.dto.DockerImageFileDTO;
import com.ctg.itrdc.imageconsole.data.entity.DockerAppImage;
import com.ctg.itrdc.imageconsole.data.entity.DockerAppType;
import com.ctg.itrdc.imageconsole.data.entity.DockerImage;
import com.ctg.itrdc.imageconsole.data.entity.DockerImageTag;
import com.ctg.itrdc.imageconsole.service.IDockerImageIndexService;
import com.ctg.itrdc.imageconsole.service.IDockerImageService;
import com.ctg.itrdc.pasp.security.utils.WebUtils;
import com.ctg.itrdc.paspsdk.common.entity.PageInfo;
import com.ctg.itrdc.paspsdk.common.utils.bean.BeanUtils;
import com.ctg.itrdc.paspsdk.common.utils.type.DateUtils;
import com.ctg.itrdc.paspsdk.common.utils.type.StringUtils;

@Component("dockerImageService")
public class DockerImageServiceImpl implements IDockerImageService {
	@Resource
	private IDockerImageDao dockerImageFileDao;

	@Resource
	private IDockerAppImageDao dockerAppImageDao;

	@Resource
	private IDockerAppTypeDao dockerAppTypeDao;

	@Resource
	private IDockerImageIndexService imageIndexService;

	@Override
	public PageInfo<DockerImageFileDTO> queryImageFilePageInfo(String imageName, String imageType, Integer currentPage,
			Integer perPageNum) {

		long userId = WebUtils.getCtgUser().getSysUserId();
		PageInfo<DockerImageFileDTO> pageInfo = dockerImageFileDao.jdbcFindPageInfo(userId, imageName, imageType, currentPage,
				perPageNum);

		if (pageInfo.getList() != null && pageInfo.getList().size() > 0) {
			for (DockerImageFileDTO dto : pageInfo.getList()) {
				// TODO 这里是由于前端那边的要求：要求后端接收与返回都是以时间撮的形式。有问题联系前端
				if (StringUtils.isNotEmpty(dto.getCreateTime())) {
					Long time = TimeUtils.parse(dto.getCreateTime()).getTime();
					dto.setCreateTime(time.toString());
				}
				if (StringUtils.isNotEmpty(dto.getLastUpdateTime())) {
					Long time = TimeUtils.parse(dto.getLastUpdateTime()).getTime();
					dto.setLastUpdateTime(time.toString());
				}

				List<DockerImageTag> indexs = imageIndexService.findByImageFileIdAndVersion(dto.getId(),
						dto.getVersion());
				if (indexs == null || indexs.size() == 0) {
					continue;
				}
			}
		}

		return pageInfo;
	}


	public void checkIsNull(DockerImageFileDTO entity) {
		if (entity == null)
			entity = new DockerImageFileDTO();
	}

	private String changeStateToName(String state) {
		String stateName = null;
		if ("001".equals(state)) {
			stateName = "正常";
		} else if ("002".equals(state)) {
			stateName = "删除";
		} else {
			stateName = "状态有误";
		}
		return stateName;
	}

	@Override
	public int updateByPrimaryKey(DockerImage entity) {
		DockerImage oldImageFile = this.selectByDockerImageFile(entity);
		oldImageFile.setTiteDesc(entity.getTiteDesc());
		oldImageFile.setContent(entity.getContent());
		oldImageFile.setState(entity.getState());
		String now = DateUtils.getCurDate();
		oldImageFile.setLastUpdateUserId(11111111L);
		oldImageFile.setLastUpdateTime(now);
		return dockerImageFileDao.updateByPrimaryKey(oldImageFile);
	}

	@Override
	public int deleteByPrimaryKey(DockerImage entity) {
		dockerAppImageDao.deleteByDockerImageFileId(entity.getId());
		DockerImage oldDockerImageFile = this.selectByDockerImageFile(entity);
		oldDockerImageFile.setState(CommonConst.DELETE_IMAGE_FILE_STATE);
		return dockerImageFileDao.updateByPrimaryKey(oldDockerImageFile);
	}

	@Override
	public List<DockerImage> selectByExample(DockerImage entity) {
		return dockerImageFileDao.selectByExample(entity);
	}

	@Override
	public String getAppNamesByDockerImageFileId(Long dockerImageFileId) {

		StringBuilder appNames = new StringBuilder("");
		if (StringUtils.isNullOrEmpty(dockerImageFileId))
			return appNames.toString();

		DockerAppImage dockerAppImage = new DockerAppImage();
		dockerAppImage.setDockerImageFileId(dockerImageFileId);
		List<DockerAppImage> dockerAppImageList = dockerAppImageDao.selectByExample(dockerAppImage);

		if (dockerAppImageList != null && dockerAppImageList.size() > 0) {
			StringBuilder ids = new StringBuilder("(");
			for (DockerAppImage dai : dockerAppImageList)
				ids.append(dai.getDockerAppTypeId()).append(",");
			ids.substring(0, ids.length() - 1);
			ids.append(")");

			List<DockerAppType> dockerAppTypeList = dockerAppTypeDao.findByIdStr(ids.toString());
			appNames.append("(");
			for (DockerAppType dat : dockerAppTypeList)
				appNames.append(dat.getAppName()).append("/");
			appNames.substring(0, appNames.length() - 1);
			appNames.append(")");
		}
		return appNames.toString();
	}

	@Override
	public DockerImage selectByDockerImageFile(DockerImage entity) {
		return dockerImageFileDao.selectByPrimaryKey(entity);
	}

	@Override
	public DockerImageFileDTO FindByPrimaryKey(Long dockerImageFileId) throws Exception {
		DockerImage dockerImageFile = new DockerImage();
		dockerImageFile.setId(dockerImageFileId);
		dockerImageFile = dockerImageFileDao.selectByPrimaryKey(dockerImageFile);

		DockerImageFileDTO difDTO = new DockerImageFileDTO();
		BeanUtils.applyIf(difDTO, dockerImageFile, true);
		difDTO.setStateName(this.changeStateToName(difDTO.getState()));

		if (StringUtils.isNotEmpty(difDTO.getCreateTime())) {
			Long time = TimeUtils.parse(difDTO.getCreateTime()).getTime();
			difDTO.setCreateTime(time.toString());
		}
		if (StringUtils.isNotEmpty(difDTO.getLastUpdateTime())) {
			Long time = TimeUtils.parse(difDTO.getLastUpdateTime()).getTime();
			difDTO.setLastUpdateTime(time.toString());
		}
		if ("0".equals(difDTO.getTenantCode())) {
			difDTO.setImageName(difDTO.getAppName());
		} else {
			difDTO.setImageName(difDTO.getTenantCode() + "/" + difDTO.getAppName());
		}
//		this.setDownloadAddr(difDTO);

		return difDTO;
	}

//	private DockerImageFileDTO setDownloadAddr(DockerImageFileDTO difDTO) {
//		List<DockerImageIndex> indexs = imageIndexService.findByImageFileIdAndVersion(difDTO.getId(),
//				difDTO.getVersion());
//		if (indexs == null || indexs.size() == 0) {
//			return difDTO;
//		}
//		Long pserverId = indexs.get(0).getDockerPserverId();
//		DockerPserver pserver = new DockerPserver();
//		pserver.setId(pserverId);
//		pserver = pserverDao.selectByPrimaryKey(pserver);
//
//		if (pserver == null) {
//			return difDTO;
//		}
//
//		// 拼接出下载地址
//		String downloadAddr = null;
//		if ("0".equals(difDTO.getTenantCode())) {
//			downloadAddr = pserver.getIpaddress() + ":" + pserver.getPort() + "/" + difDTO.getAppName();
//		} else {
//			downloadAddr = pserver.getIpaddress() + ":" + pserver.getPort() + "/" + difDTO.getTenantCode() + "/"
//					+ difDTO.getAppName();
//		}
//		difDTO.setDownloadAddr(downloadAddr);
//
//		return difDTO;
//	}

	@Override
	public boolean saveFile(byte[] bfile, String fileDirPath, String fileName) {
		FileOutputStream out = null;
		try {
			File dir = new File(fileDirPath);
			if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
				dir.mkdirs();
			}
			fileDirPath = URLDecoder.decode(fileDirPath, "UTF-8");
			out = new FileOutputStream(fileDirPath + "/" + fileName);
			out.write(bfile);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return true;
	}

}
